﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Data.Services;

namespace Kocic.RepositoryManagement.Crm4
{
    /// <summary>
    /// Defers all CRM entity objects to the context and allows changes to be pushed to the context at once.
    /// </summary>
    /// <typeparam name="TContext">The crm data context to defer changes to.</typeparam>
    public class XrmContextDeferrer<TContext> : DataSourceDeferrer<TContext, CrmEntity>
        where TContext : CrmDataContext, new()
    {
        /// <summary>
        /// Creates an instance of the XrmContextDeferrer class which uses a reference to the CRM data context defined in the scope of a XrmExecutionContext instance.
        /// </summary>
        public XrmContextDeferrer()
            : base(XrmExecutionContext<TContext>.CurrentDataSource)
        {

        }

        /// <summary>
        /// Creates an instance of the LinqToSqlContextDeferrer class
        /// </summary>
        /// <param name="context">An instance fo the CRM data context to which to defer changes to</param>
        public XrmContextDeferrer(TContext context)
            : base(context)
        {
        }

        /// <summary>
        /// Disposes unmanaged resources.
        /// </summary>
        /// <param name="disposing">Value indicating if to invoke the method from the IDisposable.Dispose implementation or from the finalizer.</param>
        protected override void Dispose(Boolean disposing)
        {
            if (disposing)
            {
                if (this.Disposed)
                {
                    return;
                }

                try
                {
                    this.DataSource.SaveChanges();
                }
                finally
                {
                    DeferralOperation = null;

                    base.Dispose(disposing);
                }
            }
        }
    }
}
